package cn.tradewin.pmp.services.download.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.tapestry5.services.Response;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

import cn.tradewin.common.util.MimeSymbols;
import cn.tradewin.pmp.services.download.OutputStreamResponse;

public class CsvOutputStreamResponse implements OutputStreamResponse {

	private final String[] columns;
	private final List<?> beans;
	private final String filename;

	public CsvOutputStreamResponse(String filename, String[] columns,
			List<?> beans) {
		this.columns = columns;
		this.beans = beans;
		this.filename = filename;
	}

	@Override
	public String getContentType() {
		return MimeSymbols.TEXT_CSV;
	}

	@Override
	public void writeToStream(OutputStream out) throws IOException {
		OutputStreamWriter streamWriter = new OutputStreamWriter(out);
		CsvBeanWriter writer = new CsvBeanWriter(streamWriter, CsvPreference.EXCEL_PREFERENCE);
		writer.writeHeader(columns);
		for (Object bean : beans) {
			writer.write(bean, columns);
		}
		writer.close();
	}

	@Override
	public void prepareResponse(Response response) {
		try {
			String output = new File(filename).getName();
			// 如果不设定该header的值，就会直接在浏览器上显示的内容。
			response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode(output, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
